/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 *  Copyright 2008 Global Sign In
 * 
 *  This code is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <stdlib.h>
#include <iostream>

#include "PHPSerializer.h"

using std::clog;
using std::endl;
using std::vector;
using std::string;

PHPSerializer::PHPSerializer()
{
}

PHPSerializer::~PHPSerializer()
{
}

bool PHPSerializer::unserializeArrayOfStrings(const string &ser, vector<string> &array)
{
	if (ser.empty() == true)
	{
		return false;
	}

	string::size_type serLen = ser.length();
	string::size_type pos = 0;
	char type = ser[pos];
	if (type != 'a')
	{
		return false;
	}

	pos += 2;
	if (pos >= serLen)
	{
		return false;
	}
	string::size_type endOfSize = ser.find(':', pos);
	if (endOfSize == string::npos)
	{
		return false;
	}
	int arraySize = atoi(ser.substr(pos, endOfSize - pos).c_str());
	if (arraySize != 1)
	{
#ifdef DEBUG
		clog << "PHPSerializer::unserializeArrayOfStrings: empty array" << endl;
#endif
		return false;
	}

	pos = endOfSize + 2;
	if (pos >= serLen)
	{
		return false;
	}
	while ((pos < serLen) &&
		(ser[pos] != '}'))
	{
		type = ser[pos];
		if (type != 's')
		{
			return false;
		}

		pos += 2;
		if (pos >= serLen)
		{
			return false;
		}
		endOfSize = ser.find(':', pos);
		if (endOfSize == string::npos)
		{
			return false;
		}
		int stringSize = atoi(ser.substr(pos, endOfSize - pos).c_str());
		if (stringSize <= 0)
		{
			return false;
		}

		pos = endOfSize + 2;
		if (pos >= serLen)
		{
			return false;
		}
		string str(ser.substr(pos, stringSize));
#ifdef DEBUG
		clog << "PHPSerializer::unserializeArrayOfStrings: found " << str << endl;
#endif
		array.push_back(str);

		pos += stringSize;
		if (pos >= serLen)
		{
			return false;
		}
		string::size_type endOfString = ser.find(';', pos);
		if (endOfString == string::npos)
		{
			return false;
		}

		pos = endOfString + 1;
	}

	return true;
}

